<template>
	<view>
		<cu-custom :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">编辑帖子</block>
		</cu-custom>
		<view class="cu-card shadow">
			<view class="cu-item">
				<form>
					<view class="cu-form-group" style="width: 100%;">
						<view class="flex justify-start align-center" style="width: 100%;">
							<view class="title">标题 :</view>
							<input v-model="title" style="font-size: 28upx;" placeholder="取个好的标题万一火了呢"
								maxlength="40"></input>
							<text class="text-sm">{{title.length}}/40</text>
						</view>
					</view>
					<!-- 					<view v-if="isManager" class="cu-form-group" style="width: 100%;">
						<view class="flex align-center" style="width: 100%;">
							<view class="title">链接 :</view>
							<input v-model="link" style="font-size: 28upx;width: 100%;" placeholder="选填,icodefuture.com下的超链接" maxlength="256"></input>
						</view>
					</view> -->
					<view class="cu-form-group align-start" style="height:calc(100vh - 1100upx)">
						<view class="title">内容 :</view>
						<textarea @input="contentUpdate" maxlength="-1" :disabled="modalName!=null" :value="content"
							placeholder="请输入内容" style="height: 90%;font-size: 30upx;line-height: 40upx;letter-spacing: 2upx;"></textarea>
					</view>
					<view class="cu-form-group">
						<view class="flex justify-between align-center" style="width: 100%;">
							<view v-if="topic==null">
								<button @tap="chooseTopicAction" class="cu-btn radius line-blue sm">#选择话题</button>
							</view>
							<view v-else class="flex justify-start align-center">
								<view @tap="chooseTopicAction" class="cu-tag radius line-blue text-cut"
									style="max-width: 65%;">#{{topic.title}}#</view>
								<text @tap="clearTopicAction" class="cuIcon-close text-gray padding-left-xs"></text>
							</view>
							<view class="flex justify-end align-center" style="min-width: 35%;">
								<view class="padding-right flex justify-start align-center">
									<button @tap="chooseForum" class="cu-btn sm round text-sm lines-mauve text-red"
										style="min-width: 120upx;">{{forum.name}}</button>
									<text v-if="forum.forum_id>1" @tap="clearForumAction"
										class="cuIcon-close text-gray padding-left-xs"></text>
								</view>
							</view>
						</view>
					</view>
					<view class="cu-bar bg-white flex justify-between align-center solid-top">
						<view class="action">
							上传图片 (最多四张 )
						</view>
					</view>
					<view class="cu-form-group">
						<view class="grid col-4 grid-square flex-sub padding-bottom">
							<view class="bg-img" v-for="(item,index) in imgList" :key="index" @click="ViewImage"
								:data-url="item.local">
								<image
									:class="(item.is_uping==false&&item.remote==null)||(item.is_uping==true)?'bg-mask':''"
									:src="item.local" mode="aspectFill"></image>
								<view class="cu-load load-cuIcon text-white padding-top"
									:class="item.is_uping?'loading':'over'"></view>
								<view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index">
									<text class='cuIcon-close'></text>
								</view>
								<view v-if="item.is_uping==false&&item.remote==null">
									<view @click.stop="retryUpload(item,index)"
										style="position: absolute;z-index: 2;top: 40upx;right: 25upx;">
										<view class="flex justify-center align-center" style="flex-direction: column;">
											<text class="text-white sm">上传失败</text>
											<text class="text-white sm">点击重试</text>
										</view>
									</view>
								</view>
							</view>
							<view class="solids" @tap="ChooseImage" v-if="imgList.length<4">
								<text class='cuIcon-cameraadd'></text>
							</view>
						</view>
					</view>
					<view v-if="isManager" class="cu-form-group">
						<view class="flex justify-between align-center" style="width: 100%;">
							<view class="flex justify-start align-center">
								<view class="label text-df padding-right">视频:</view>
								<view v-if="requestStatus.upingVideoSuccess&&!requestStatus.isUpingVideo"
									@tap="ViewVideo" class="cu-avatar radius"
									:style="'background-image: url('+imgList[0].remote+'?imageView2/2/w/200/h/200/q/75);'">
								</view>
								<view v-else @tap="ViewVideo" class="cu-avatar radius"
									:style="'background-image: url('+imgList[0].remote+');'"></view>
								<view class="flex justify-start align-center">
									<view class="padding-left cu-load load-cuIcon"
										:class="requestStatus.isUpingVideo?'loading':'over'"></view>
									<view v-if="requestStatus.isUpingVideo">
										<text class="padding-left-xs text-grey text-sm">上传中</text>
									</view>
									<view v-if="localVideo.length>0&&requestStatus.isUpingVideo==false">
										<text
											class="padding-left-xs text-grey text-sm">{{requestStatus.upingVideoSuccess?'上传成功':'上传失败'}}</text>
									</view>
								</view>
							</view>
							<view @tap="chooseVideo" class="action lines-grey flex justify-center align-center solid">
								<text class="cuIcon-camera text-grey padding-sm"></text>
							</view>
						</view>
					</view>
					<view v-if="isManager" class="cu-form-group">
						<view class="flex justify-between align-center" style="width: 100%;">
							<view class="flex justify-start align-center padding-right-sm" style="width: 50%;">
								<text class="text-df text-left" style="min-width: 100upx;">小程序:</text>
								<view @tap="chooseMiniProgramAction" class="cu-tag radius line-cyan radius text-sm padding-left-xs"
									style="height: 50upx;">{{miniProgram==null?'选择小程序关联':miniProgram.short_name}}
								</view>
							</view>
							<view class="flex justify-end align-center" style="width: 50%;">
								<text class="text-df padding-right-xs text-right" style="min-width: 100upx;">公众号:</text>
								<view @tap="chooseOfficialAccountAction"
									class="cu-tag radius line-olive radius text-sm" style="height: 50upx;">
									{{officialAccount==null?'选择公众号关联':officialAccount.name}}
								</view>
							</view>
						</view>
					</view>
					<view class="cu-form-group" style="width: 100%;">
						<view @tap="jumpToAddDoc" class="flex justify-between align-center" style="width: 100%;">
							<view class="title">腾讯文档 :</view>
							<view class="flex justify-end align-center">
								<view v-if="docList.length>0" class="cu-tag bg-blue">已添加{{docList.length}}个文档</view>
								<text class="cuIcon-right text-grey"></text>
							</view>
						</view>
					</view>
				</form>
			</view>
			<view class="action flex justify-center align-center padding-top padding-bottom" style="width: 100%;">
				<button @tap="commitAction" :class="'cu-btn round '+themeColor" style="width: 70%;">确定发布</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getUserInfo
	} from '@/api/auth.js'
	import {
		createPost,
		uploadImage,
		postDetail,
		updatePost,
		uploadFile
	} from '@/api/api.js'
	export default {
		data() {
			return {
				docList:[],
				topic: null,
				appSetting: this.AppSetting,
				themeColor: this.ThemeColor,
				forum: {
					forum_id: 1,
					name: '主板块'
				},
				miniProgram: null,
				officialAccount: null,
				postId: null,
				post: null,
				content: '',
				title: '',
				link: '',
				vote: {},
				imgList: [],
				imgModify: false,
				localVideo: '',
				requestStatus: {
					isUpingVideo: false,
					upingVideoSuccess: false
				}
			}
		},
		onLoad(options) {
			if (options.postId !== null && options.postId !== undefined) {
				this.postId = options.postId
				this.getPostDetail()
			}
		},
		computed: {
			isManager() {
				let userInfo = getUserInfo()
				if (userInfo.role == null) {
					return false
				}
				if (this.appSetting.enable_user_video == 1) {
					return true
				}
				//是不是认证用户
				if (userInfo.group && userInfo.group.open_choose == 0) {
					return true
				}
				return userInfo.role_id > 0
			}
		},
		methods: {
			jumpToAddDoc()
			{
				let that = this
				uni.navigateTo({
					url:'/pages/lessuse/add-doc/add-doc',
					success:function(res){
						res.eventChannel.emit('addDoc',that.docList)
					},
					events:{
						commitEvent:function(data) {
							that.docList = data
						}
					}
				})
			},
			clearForumAction() {
				this.forum = {
					forum_id: 1,
					name: '主板块'
				}
			},
			clearTopicAction() {
				this.topic = null
			},
			chooseTopicAction() {
				let that = this
				uni.navigateTo({
					url: '/pages/always/topic-list/topic-list',
					events: {
						finishChoose: function(data) {
							that.topic = data
						}
					}
				})
			},
			chooseVideo() {
				let that = this
				uni.chooseVideo({
					count: 1,
					maxDuration: 15,
					compressed: false,
					sourceType: ['camera', 'album'],
					success: function(res) {
						that.localVideo = res.tempFilePath;
						//上传视频
						let timestamp = new Date().getTime()
						let fileKey = String(timestamp) + '_' + res.width + '_' + res.height + '.mp4'
						that.requestStatus.isUpingVideo = true
						uploadFile(res.tempFilePath, fileKey, remoteUrl => {
							that.link = remoteUrl
							that.requestStatus.isUpingVideo = false
							that.requestStatus.upingVideoSuccess = true
						}, error => {
							console.log(error)
							that.requestStatus.isUpingVideo = false
							that.requestStatus.upingVideoSuccess = false
						})
					}
				});
			},
			chooseForum() {
				let that = this
				uni.navigateTo({
					url: '/pages/always/forum-list/forum-list?isPublish=1',
					events: {
						finishChoose: function(data) {
							that.forum = data
						}
					}
				})
			},
			chooseMiniProgramAction() {
				let that = this
				uni.navigateTo({
					url: '/pages/always/mini-program-list/mini-program-list?isPublish=1',
					events: {
						finishChoose: function(data) {
							that.miniProgram = data
						}
					}
				})
			},
			chooseOfficialAccountAction() {
				let that = this
				uni.navigateTo({
					url: '/pages/always/official-account-list/official-account-list?isPublish=1',
					events: {
						finishChoose: function(data) {
							that.officialAccount = data
						}
					}
				})
			},
			retryUpload(item, index) {
				this.imgList[index].is_uping = true
				uploadImage(item.local, item.fileKey, (imgUrl) => {
					console.log(imgUrl)
					this.imgList[index].remote = imgUrl
					this.imgList[index].is_uping = false
				}, (error) => {
					this.imgList[index].is_uping = false
				})
			},
			getPostDetail() {
				if (this.postId == null) {
					return
				}
				uni.showLoading({
					title: '正在加载...'
				})
				postDetail(this.postId).then(res => {
					uni.hideLoading()
					this.post = res.data
					this.content = res.data.content
					this.title = res.data.title
					this.link = res.data.link
					this.miniProgram = res.data.mini_program
					this.officialAccount = res.data.official_account
					this.forum = res.data.forum
					this.topic = res.data.topic
					this.docList = res.data.document_list
					if (res.data.image_list && res.data.image_list.length > 0) {
						res.data.image_list.forEach(url => {
							let item = {
								'local': url,
								'remote': url,
								'is_uping': false,
							}
							this.imgList.push(item)
						})
					}
				}).catch(error => {
					uni.hideLoading()
				})
			},
			contentUpdate(e) {
				this.content = e.detail.value
			},
			commitAction() {
				if (this.post == null) {
					uni.showToast({
						icon: 'none',
						title: '无法编辑空内容!'
					})
					return
				}
				if (this.content.length > 5000) {
					uni.showToast({
						icon: 'none',
						title: '内容不可超过5000字'
					})
				}
				if (this.title.length > 40) {
					uni.showToast({
						icon: 'none',
						title: '标题不可超过40字'
					})
				}

				let params = {}
				if (this.title != this.post.title) {
					params['title'] = this.title
				}
				if (this.content != this.post.content) {
					params['content'] = this.content
				}
				if (this.link != this.post.link) {
					params['link'] = this.link
				}

				if (params.link && params.link.length > 0) {
					//视频帖必须要有封面图
					if (params.link.indexOf('.mp4') !== -1) {
						let upImageList = [];
						this.imgList.forEach(item => {
							if (item.remote !== null) {
								upImageList.push(item.remote)
							}
						})
						if (upImageList.length == 0) {
							uni.showToast({
								icon: 'none',
								title: '视频贴必须上传封面图!'
							})
							return
						}
					}
				}

				if (this.miniProgram !== null) {
					params['programId'] = this.miniProgram.program_id
				}

				if (this.officialAccount !== null) {
					params['accountId'] = this.officialAccount.account_id
				}

				if (this.forum !== null) {
					params['forumId'] = this.forum.forum_id
				}

				if (this.imgList.length > 0 && this.imgModify) {
					let upImageList = [];
					this.imgList.forEach(item => {
						if (item.remote !== null) {
							upImageList.push(item.remote)
						}
					})
					if (upImageList.length > 0) {
						params['imageList'] = upImageList
					}
				}
				params['documents'] = this.docList
				uni.showLoading({
					title: '正在发布...'
				})
				params['postId'] = this.post.post_id
				updatePost(params).then(res => {
					uni.hideLoading()
					let postId = res.data.post_id
					uni.showModal({
						title: '更新成功',
						cancelText: '取消',
						confirmText: '查看帖子',
						success(res) {
							if (res.confirm) {
								uni.redirectTo({
									url: '/pages/detail/detail?postId=' + postId
								})
							}
						}
					})
				}).catch(error => {
					uni.hideLoading()
				})

			},
			openVote() {
				let that = this
				uni.navigateTo({
					url: '/pages/lessuse/vote/vote',
					events: {
						// 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
						commitEvent: function(data) {
							console.log(data)
							that.vote = data.vote
						}
					},
					success: function(res) {
						// 通过eventChannel向被打开页面传送数据
						if (that.vote && that.vote.voteItemList.length > 0) {
							res.eventChannel.emit('acceptDataFromOpenerPage', {
								vote: that.vote
							})
						}
					}
				})
			},
			ChooseImage() {
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					success: (res) => {
						let timestamp = new Date().getTime()
						let fileKey = String(timestamp)
						let item = {
							'local': res.tempFilePaths[0],
							'remote': null,
							'is_uping': false,
							'fileKey': fileKey,
						}
						this.imgList.push(item)
						let index = this.imgList.length - 1
						this.imgList[index].is_uping = true
						uploadImage(res.tempFilePaths[0], fileKey, (imgUrl) => {
							console.log(imgUrl)
							this.imgList[index].remote = imgUrl
							this.imgList[index].is_uping = false
						}, (error) => {
							this.imgList[index].is_uping = false
						})
					}
				});
			},
			ViewImage(e) {
				console.log(this.imgList)
				console.log(e.currentTarget.dataset.url)
				let currentUrl = e.currentTarget.dataset.url
				if (currentUrl == null || currentUrl.length == 0) {
					return
				}
				let previewImgList = []
				this.imgList.forEach(item => {
					previewImgList.push(item.local)
				})
				uni.previewImage({
					urls: previewImgList,
					current: e.currentTarget.dataset.url
				});
			},
			DelImg(e) {
				uni.showModal({
					title: '提示',
					content: '确定要删除这张图片吗？',
					cancelText: '取消',
					confirmText: '确定',
					success: res => {
						if (res.confirm) {
							this.imgModify = true
							this.imgList.splice(e.currentTarget.dataset.index, 1)
						}
					}
				})
			},
		}
	}
</script>

<style>

</style>
